#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
图标管理器
支持SVG动态着色和主题切换
"""

import os
from PyQt5.QtGui import QIcon, QPixmap, QPainter, QColor
from PyQt5.QtSvg import QSvgRenderer
from PyQt5.QtCore import Qt, QSize


class IconManager:
    """图标管理器 - 支持SVG动态着色"""
    
    # 图标主题配置
    THEMES = {
        'dark': {
            'default': '#ffffff',
            'hover': '#1890ff',
            'pressed': '#0078d4',
            'disabled': '#666666',
            'checked': '#1890ff'
        },
        'light': {
            'default': '#000000',
            'hover': '#0078d4',
            'pressed': '#005a9e',
            'disabled': '#999999',
            'checked': '#0078d4'
        }
    }
    
    def __init__(self, icons_dir=None, theme='dark'):
        """
        初始化图标管理器
        
        Args:
            icons_dir: 图标目录路径
            theme: 主题名称 ('dark' 或 'light')
        """
        self.icons_dir = icons_dir or self._get_default_icons_dir()
        self.theme = theme
        self._cache = {}  # 图标缓存 {name: QIcon}
    
    def _get_default_icons_dir(self):
        """获取默认图标目录"""
        current_dir = os.path.dirname(os.path.abspath(__file__))
        return os.path.join(current_dir, 'icons')
    
    def get_icon(self, name, size=24):
        """
        获取图标
        
        Args:
            name: 图标名称(不含扩展名)
            size: 图标尺寸
            
        Returns:
            QIcon对象
        """
        cache_key = f"{name}_{self.theme}_{size}"
        
        if cache_key in self._cache:
            return self._cache[cache_key]
        
        # 构建SVG文件路径
        svg_path = os.path.join(self.icons_dir, f"{name}.svg")
        
        if not os.path.exists(svg_path):
            print(f"图标文件不存在: {svg_path}")
            return QIcon()
        
        # 创建多状态图标
        icon = self._create_multi_state_icon(svg_path, size)
        
        # 缓存
        self._cache[cache_key] = icon
        
        return icon
    
    def _create_multi_state_icon(self, svg_path, size):
        """
        创建支持多状态的图标
        
        Args:
            svg_path: SVG文件路径
            size: 图标尺寸
            
        Returns:
            QIcon对象
        """
        icon = QIcon()
        theme = self.THEMES[self.theme]
        
        # Normal状态
        pixmap_normal = self._render_svg(svg_path, size, theme['default'])
        icon.addPixmap(pixmap_normal, QIcon.Normal, QIcon.Off)
        
        # Disabled状态
        pixmap_disabled = self._render_svg(svg_path, size, theme['disabled'])
        icon.addPixmap(pixmap_disabled, QIcon.Disabled)
        
        # Active状态 (hover)
        pixmap_active = self._render_svg(svg_path, size, theme['hover'])
        icon.addPixmap(pixmap_active, QIcon.Active)
        
        # Selected状态 (checked)
        pixmap_selected = self._render_svg(svg_path, size, theme['checked'])
        icon.addPixmap(pixmap_selected, QIcon.Selected)
        icon.addPixmap(pixmap_selected, QIcon.Normal, QIcon.On)
        
        return icon
    
    def _render_svg(self, svg_path, size, color):
        """
        渲染SVG为指定颜色的Pixmap
        
        Args:
            svg_path: SVG文件路径
            size: 尺寸
            color: 颜色(十六进制字符串)
            
        Returns:
            QPixmap对象
        """
        # 读取SVG内容
        with open(svg_path, 'r', encoding='utf-8') as f:
            svg_content = f.read()
        
        # 替换颜色 (将currentColor或stroke替换为指定颜色)
        svg_content = svg_content.replace('currentColor', color)
        svg_content = svg_content.replace('stroke="#000000"', f'stroke="{color}"')
        svg_content = svg_content.replace('stroke="#000"', f'stroke="{color}"')
        svg_content = svg_content.replace('fill="#000000"', f'fill="{color}"')
        svg_content = svg_content.replace('fill="#000"', f'fill="{color}"')
        
        # 渲染
        renderer = QSvgRenderer(svg_content.encode('utf-8'))
        pixmap = QPixmap(QSize(size, size))
        pixmap.fill(Qt.transparent)
        
        painter = QPainter(pixmap)
        renderer.render(painter)
        painter.end()
        
        return pixmap
    
    def set_theme(self, theme):
        """
        切换主题
        
        Args:
            theme: 主题名称 ('dark' 或 'light')
        """
        if theme in self.THEMES:
            self.theme = theme
            self._cache.clear()  # 清空缓存
    
    def get_icon_path(self, name):
        """
        获取图标文件路径
        
        Args:
            name: 图标名称(不含扩展名)
            
        Returns:
            完整文件路径
        """
        return os.path.join(self.icons_dir, f"{name}.svg")
    
    def clear_cache(self):
        """清空图标缓存"""
        self._cache.clear()
    
    @staticmethod
    def create_colored_icon(svg_path, color, size=24):
        """
        静态方法：创建单色图标
        
        Args:
            svg_path: SVG文件路径
            color: 颜色字符串
            size: 尺寸
            
        Returns:
            QIcon对象
        """
        manager = IconManager()
        pixmap = manager._render_svg(svg_path, size, color)
        icon = QIcon()
        icon.addPixmap(pixmap)
        return icon


# 全局图标管理器实例
_global_icon_manager = None


def get_icon_manager(theme='dark'):
    """获取全局图标管理器实例"""
    global _global_icon_manager
    
    if _global_icon_manager is None:
        _global_icon_manager = IconManager(theme=theme)
    
    return _global_icon_manager


def set_icon_theme(theme):
    """设置全局图标主题"""
    global _global_icon_manager
    
    if _global_icon_manager:
        _global_icon_manager.set_theme(theme)
    else:
        _global_icon_manager = IconManager(theme=theme)
